import React, { useState, useEffect } from "react";
import cls from "classnames";

import style from "./index.module.scss";
import Link from "next/link";
import { Spin } from "antd";
import { ArticleList } from "../ArticleList";
import { SearchApi } from "@/api/search";

interface IProps {
  visible: boolean;
  onClose: () => any;
}
export const Search: React.FC<IProps> = ({ visible, onClose }) => {
  const [hasSearch, sethasSearch] = useState(false);
  const [keyword, setKeyword] = useState("");
  const [article, setArticle] = useState(null);
  const [hasResult, setHasResult] = useState(false);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    setHasResult(!!article?.length);
  }, [article]);
  useEffect(() => {
    setKeyword("");
    setHasResult(null);
    sethasSearch(false);
    if (visible) {
      document.body.classList.add("fixed");
    } else {
      document.body.classList.remove("fixed");
    }
  }, [visible]);
  const getArticles = keyword => {
    sethasSearch(true);
    setLoading(true);
    SearchApi.searchArticle(keyword)
      .then(res => {
        setArticle(res);
      })
      .catch()
      .finally(() => {
        setTimeout(() => {
          setLoading(false);
        }, 500);
      });
  };
  return (
    <div className={cls(style.container, visible ? style.active : null)}>
      <div className={style.wrapper}>
        <div className={cls(style.searchBox, hasSearch ? style.active : null)}>
          <input
            className={style.searchInput}
            placeholder="Input Keyword"
            value={keyword}
            onChange={e => setKeyword(e.target.value)}
            onKeyPress={e => {
              if (e.nativeEvent.keyCode === 13) {
                if (keyword) {
                  getArticles(keyword);
                }
              }
            }}
          />
          <button onClick={onClose}>×</button>

          {loading && (
            <Spin className={style.loading} tip="搜索中" spinning={true} />
          )}
        </div>

        {hasSearch && !loading && (
          <div className={cls(style.result, hasResult ? style.active : null)}>
            {hasResult ? (
              <ArticleList asCard articles={article} onChange={onClose} />
            ) : (
              <p className={style.none}>暂未搜索到结果</p>
            )}
          </div>
        )}
      </div>
    </div>
  );
};
